<?php
namespace app\admin\controller;

use app\common\model\Banner as BannerModel;
/**
 * 广告管理
 */
class Banner extends Admin 
{
	/**
	 * 广告列表
	 * @return array
	 */
	public function index(){
		$map = [];
		$list = BannerModel::where($map)->order('id desc')->paginate(15);

		$this->assign('list', $list);
		return $this->fetch();
	}

	/**
	 * 新增广告
	 */
	public function add(){
		if($this->request->isPost()){
			$data = $this->request->post();
			// 验证
            $result = $this->validate($data, [
                'name|广告名称' => 'require',
                'thumb|广告图片' => 'require'
            ]);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            if($res = BannerModel::create($data)){
            	$this->success('新增成功');
            }else{
            	$this->error('新增失败');
            }
		}else{
			$this->assign('info', null);
			return $this->fetch('edit');
		}
	}

	/**
	 * 编辑广告
	 */
	public function edit($id = 0){
		if($this->request->isPost()){
			$data = $this->request->post();
			// 验证
            $result = $this->validate($data, [
                'name|广告名称' => 'require',
                'thumb|广告图片' => 'require'
            ]);
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            if($res = BannerModel::update($data)){
            	$this->success('编辑成功');
            }else{
            	$this->error('编辑失败');
            }
		}else{
			empty($id) && $this->error('参数错误');

			$info = BannerModel::where('id',$id)->find();

			$this->assign('info', $info);
			return $this->fetch();
		}
	}

	/**
	 * 更新状态
	 * @return mixed
	 */
	public function update(){
		$data = $this->request->param();

		if(empty($data)){
			$this->error('参数错误');
		}

		if($query = BannerModel::update($data)){
            $this->success('更新成功');
        }else{
            $this->error('更新失败');
        }
	}

	/**
	 * 删除广告
	 */
	public function del($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
            $map[] = ['id','in',$id];
        }elseif(is_numeric($id)){
            $map[] = ['id','=',$id];
        }

        if($query = BannerModel::where($map)->delete()){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
	}
}